package com.xaicode.auth.config.satoken;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.xaicode.auth.config.properties.SystemProperties;
import com.xaicode.auth.security.support.ExcludeUriPatternsLoader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * SaToken 配置
 * 
 * @date 2024/12/9
 */
@Slf4j
@Configuration
public class SaTokenConfigurer implements WebMvcConfigurer {

    @Autowired
    private SystemProperties systemProperties;

    private static final List<String> DEFAULT_EXCLUDE_URIS = Collections.emptyList();

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        /*
            !!! 此配置仅用于 asl-auth 模块。
         */

        List<String> excludeUriPatterns = new ArrayList<>();
        // 加载内部默认忽略请求路径
        excludeUriPatterns.addAll(DEFAULT_EXCLUDE_URIS);
        // 加载配置文件中的忽略请求路径
        excludeUriPatterns.addAll(systemProperties.getSecurity().getExcludeUriPatterns());
        // 加载通过指定接口获取的忽略请求路径
        excludeUriPatterns.addAll(ExcludeUriPatternsLoader.all());

        registry.addInterceptor(
                        /* 添加 Sa-Token 拦截器 */
                        new SaInterceptor(handler -> {
                            SaRouter.match("/**")
                                    .notMatch(excludeUriPatterns)
                                    .check(r -> StpUtil.checkLogin());
                        })
                )
                .addPathPatterns("/**");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 开放跨域访问
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("*")
                .allowCredentials(false)
                .maxAge(3600);
    }
}
